import router from '../router'
import { local, getQueryString } from '@assets/js/global'
import { getWxUserInfo, isFirstBind, alreadyRegister } from '@/api'

const appId = 'wx2d4f16576d62d27c'
const redirectUrl = 'http://www.koudaiyundong.com/gwgreen/sports/index.html'
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
let code = getQueryString('code')
if (!code) {
    window.location.href = url
} else if (code) {
    local.set('code', code)
    getCode(code)
}


function getCode (code) {
  if (local.get('userInfo')) {
    isAlreadyRegister(local.get('userInfo').openid)
    } else {
        getWxUserInfo({code}).then(res => {
          console.log(res)
          if (res.result.openid) {
            local.set('userInfo', res.result)
            isAlreadyRegister(res.result.openid)
          } else {
              router.push('/index')
          }
        })
    }
}

function isAlreadyRegister (openid) {
    alreadyRegister(openid).then(data => {
      console.log(data)
      if (data.data == '0') {
        isFirstBind({openid}).then(res =>  {
          console.log(res)
          if (res.data) {
            console.log('index')
            router.push('/index')
          } else {
            console.log(222)
            window.location.href = 'https://h5.youzan.com/v2/showcase/homepage?alias=0vc7r34yT0'
          }
        })
      } else if (data.data == '1') {
        console.log('/reg')
        router.push('/register')
      }
    })
}